//
//  QDLoginViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/27.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit



/// 登陆
final class QDLoginViewController: NWViewController,QDTimeVerifier {

    /// 关闭按钮
    let closeButton = UIButton()
    /// 大标题的标签
    let largeTitleLabel = UILabel()
    /// 展示请输入手机号登陆的标签
    let subtitleLabel = UILabel()
    /// 填写手机号的文本
    let phoneTextField = QDLoginPhoneTextField()
    /// 验证码按钮
    let codeButton = UIButton()
    /// 渐变色的layer
    let gradLayer = CAGradientLayer()
    /// 计时器
    private var timer: Timer?
    /// 登陆完成的回调
    @objc var loginComplete: (()->(Void))?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addUIControlHandlerTarget(self, action: #selector(endEditing))

        // Do any additional setup after loading the view.
        closeButton.backgroundColor = .clear
        closeButton.adjustsImageWhenHighlighted = false
        closeButton.setImage("login_close".namedImage, for: .normal)
        closeButton.addTarget(self, action: #selector(dismissLogin), for: .touchUpInside)
        
        largeTitleLabel.text = "登录"
        largeTitleLabel.textColor = QDColors.black
        largeTitleLabel.font = Font.semibold.font(size: 28)
        
        subtitleLabel.text = "请输入手机号登录"
        subtitleLabel.textColor = QDColors.black
        subtitleLabel.font = Font.light.font(size: 16)
        
        codeButton.setTitle("发送验证码", for: .normal)
        codeButton.adjustsImageWhenDisabled = false
        codeButton.setTitleColor(.white, for: .normal)
        codeButton.setTitleColor(.white, for: .disabled)
        codeButton.titleLabel?.font = Font.medium.font(size: 16)
        codeButton.layer.cornerRadius = 52 / 2
        codeButton.clipsToBounds = true
        
        
        gradLayer.position = .zero
        gradLayer.anchorPoint = .zero
        gradLayer.bounds = CGRect(origin: .zero, size: CGSize(width: ritl_width - 20 * 2, height: 52))
        codeButton.layer.insertSublayer(gradLayer, at: 0)
        codeButton.addTarget(self, action: #selector(sendCode), for: .touchUpInside)
        
        phoneTextField.tintColor = QDColors.theme
        phoneTextField.textColor = QDColors.black
        phoneTextField.font = Font.semibold.font(size: 20)
        phoneTextField.delegate = self
        phoneTextField.keyboardType = .numberPad
        phoneTextField.clearButtonMode = .always
        phoneTextField.attributedPlaceholder = NSAttributedString(string: "请输入手机号", attributes: [.font : Font.light.font(size: 20),.foregroundColor: #colorLiteral(red: 0.7607843137, green: 0.768627451, blue: 0.7647058824, alpha: 1)])
        
        let lineView = UIView()
        lineView.backgroundColor = #colorLiteral(red: 0.7607843137, green: 0.768627451, blue: 0.7647058824, alpha: 1)
        
        view.addSubview(closeButton)
        view.addSubview(largeTitleLabel)
        view.addSubview(subtitleLabel)
        view.addSubview(phoneTextField)
        view.addSubview(lineView)
        view.addSubview(codeButton)
        
        closeButton.snp.makeConstraints { (make) in
            make.width.height.equalTo(32)
            make.top.equalToSuperview().offset(57 + BarDistance.NavigationBar.safeDistance)
            make.left.equalToSuperview().offset(10)
        }
        
        largeTitleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.height.equalTo(40)
            make.top.equalTo(closeButton.snp.bottom).offset(36)
        }
        
        subtitleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.top.equalTo(largeTitleLabel.snp.bottom).offset(8)
            make.height.equalTo(22)
        }
        
        phoneTextField.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.height.equalTo(28)
            make.right.equalToSuperview().inset(20)
            make.top.equalTo(subtitleLabel.snp.bottom).offset(80)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().inset(20)
            make.height.equalTo(0.5)
            make.top.equalTo(phoneTextField.snp.bottom).offset(16)
        }
        
        codeButton.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().inset(20)
            make.height.equalTo(52)
            make.top.equalTo(lineView.snp.bottom).offset(40)
        }
        
        //默认不可用
        updateButtonLayer()
        
        //订阅登陆成功的回调
        NotificationCenter.default.addObserver(self, selector: #selector(catchLoginCompleteNotification), name: QDLoginCompleteNotificationName, object: nil)
        
        //如果存在过用户登录，自动填写手机
//        phoneTextField.text = QDUserInfoModel.share.phone
    }
    
    /// 接收到登陆成功的回调
    @objc func catchLoginCompleteNotification(){
        loginComplete?()
        print("登陆成功")
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        phoneTextField.becomeFirstResponder()
        //开始验证
        if !checkTimeIsOut(key: CodeRegisterTimerKey) {
            //开始验证
            startTimer(compareTime: self.time(key: CodeRegisterTimerKey))
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        timer?.invalidate()
        timer = nil
    }
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    // MARK: Timer
    
    /// 开始计时器检测
    func startTimer(compareTime: Int) {
        
        if self.timer != nil {
            return;
        }
        
        // 开启轮训
        self.timer = RITLTimer.scheduledTimer(withTimeInterval: 1.0, userInfo: [:], repeats: true, blockHandle: { [weak self] (_) in
            
            guard let strongSelf = self else { return }
            
            //获得当前时间
            let currentTime = Int(Date().timeIntervalSince1970)
            let distance = currentTime - compareTime
            
            if distance >= strongSelf.limitTime {//表示验证码可以进行
                strongSelf.timer?.invalidate()
                strongSelf.timer = nil
                strongSelf.updateButtonLayer(canUse: true)
                strongSelf.codeButton.setTitle("发送验证码", for: .disabled)
            }else {//表示做限制
                strongSelf.updateButtonLayer(canUse: false)
                strongSelf.codeButton.setTitle("\(strongSelf.limitTime - distance)", for: .disabled)
            }
        })
    }
    
    
    
    //MARK: NavigationBar
    override var nav_barHidden: Bool { return true }
    
    //MARK: Layer
    
    /// 修改layer的背景色
    func updateButtonLayer(canUse: Bool = false){
        
        codeButton.isEnabled = canUse
        
        var leftColor = QDColors.theme.withAlphaComponent(canUse ? 1 : 0.4)
        var rightColor = #colorLiteral(red: 0.4509803922, green: 0.8705882353, blue: 0.5215686275, alpha: 1).withAlphaComponent(canUse ? 1 : 0.4)
        
        //交换
        (leftColor, rightColor) = (rightColor, leftColor)
        gradLayer.colors = [leftColor.cgColor,rightColor.cgColor]
    }

    
    //MARK: Dimiss
    
    /// 模态弹出
    @objc func dismissLogin(){
        navigationController?.dismiss(animated: true, completion: nil)
    }
    
    /// 发送验证码
    @objc func sendCode(){
        print("发送验证码");
        endEditing()
        let codeViewController = QDLoginCodeViewController()
        codeViewController.phone = QDStringHelper.phone(phoneTextField.text!)
        codeViewController.backHandler = {[unowned self](distance) in
            
            // 用于修改返回状态
            if distance == 0 {
                self.updateButtonLayer(canUse: true)
            }else {
                self.updateButtonLayer(canUse: false)
                self.codeButton.setTitle("\(distance)", for: .disabled)
            }
        }
        
        
        ritl_topNavigationPush(codeViewController, animated: true)
    }
    
    /// 结束响应
    @objc func endEditing(){
        view.endEditing(true)
    }
}


extension QDLoginViewController: UITextFieldDelegate {
    
    /// 手机格式
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        return QDStringHelper.textField(textField, shouldChangeCharactersIn: range, replacementString: string, complete: {
            
            // 如果还在倒计时中
            if self.timer != nil  { return }
            //主动检测更新状态
            self.phoneTextFieldDidEditing()
        });
    }
    
    
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        textField.text = ""
        phoneTextFieldDidEditing()// 进行按钮验证
        return true
    }
    
    /// 手机文本变化
    fileprivate func phoneTextFieldDidEditing() {
        
        let phone = QDStringHelper.phone(phoneTextField.text ?? "")
        /// 更新是否是合法手机号
        updateButtonLayer(canUse: (phone as NSString).ritl_predicatedMatches("0?(13|14|15|16|17|18|19)[0-9]{9}"))
    }
}



